package com.wtgroup.demo.mianshi.线程;

import java.io.IOException;
import java.io.PipedReader;
import java.io.PipedWriter;

/**
 * @author dafei
 * @version 0.1
 * @date 2020/8/17 14:14
 */
public class Piped {

    public static void main(String[] args) throws IOException {
        PipedWriter out = new PipedWriter();
        PipedReader in = new PipedReader();
        // 连接 out 和 in , 否则抛 IOException (因为 sink==null)
        out.connect(in); // out.sink=in
        Thread printThread = new Thread(new Print(in), "PrintThread");
        printThread.start();
        int rec = 0;
        try {
            while ((rec = System.in.read()) != -1) {
                out.write(rec); // out 写入内容后, in 就会退出阻塞, 打印内容
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
        }

    }

    static class Print implements Runnable {

        private final PipedReader in;

        public Print(PipedReader in) {
            this.in = in;
        }


        @Override
        public void run() {
            int rec = 0;
            try {
                while ((rec = in.read()) != -1) { // in 在发现空时会自旋等待(wait(1000)), 当write有写入时(in==out)会唤醒read线程
                    System.out.println((char) rec);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
